package com.doufeng.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doufeng.common.dto.dispatch.TaskCreateDTO;
import com.doufeng.common.exception.BizException;
import com.doufeng.common.result.Result;
import com.doufeng.order.entity.Order;
import com.doufeng.order.feign.DispatchClient;
import com.doufeng.order.mapper.OrderMapper;
import com.doufeng.order.service.OrderService;
import com.doufeng.order.util.OrderNoGenerator;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    private DispatchClient dispatchClient;

    @Override
    @Transactional
    public boolean saveOrder(Order order) {
        // 1. 生成流水号
        order.setOrderNo(OrderNoGenerator.generate());
        // 2. 状态初始
        order.setStatus(0);
        order.setDeleted(0);
        // 3. 写入
        return this.save(order);
    }

    @Override
    @Transactional
    public void paySuccess(String orderNo) {
        Order order = this.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
        if (order == null || (!order.getStatus().equals(0))) {
            throw new BizException("订单状态异常");
        }
        // 1. 变状态
        order.setStatus(1);   // 1 = PAID
        this.updateById(order);

        // 支付成功后，创建可抢任务 + Geo 索引
        TaskCreateDTO dto = new TaskCreateDTO();
        dto.setOrderId(order.getId());
        dto.setLng(order.getLng());
        dto.setLat(order.getLat());

        try {
            logger.info("开始调用dispatch服务创建任务，订单ID: {}", order.getId());
            Result<Long> taskResult = dispatchClient.createTask(dto);
            if (taskResult.getCode() != 200) {
                // 记录错误日志，但不抛出异常，避免影响主流程
                logger.error("任务生成失败：{}，订单ID: {}", taskResult.getMsg(), order.getId());
            } else {
                logger.info("任务创建成功，任务ID: {}，订单ID: {}", taskResult.getData(), order.getId());
            }
        } catch (Exception e) {
            // 服务调用异常，记录日志但不中断主流程
            logger.error("调用dispatch服务异常，订单ID: " + order.getId() + "，错误信息: " + e.getMessage(), e);
            // 可以在这里添加其他容错处理，例如将任务信息存入数据库，后续重试等
        }
    }
}